<template>
  <div class="about">
    <div id="mm"></div>
    <el-container>
      <el-header style="height: 62px;background-color: #545c64">
        <h2 style="float: left; color: azure; margin-top: 15px">当前词库：{{ library }}</h2>
        <el-menu class="el-menu-demo"
                 default-active="1"
                 mode="horizontal"
                 background-color="#545c64"
                 text-color="#fff"
                 active-text-color="#ffd04b"
                 @select="handleSelect">
          <el-dialog title="添加单词" :visible.sync="dialogFormVisible" center>
            <el-form :model="form">
              <el-form-item label="English" :label-width="formLabelWidth">
                <el-input v-model="form.name" ></el-input>
              </el-form-item>
              <el-form-item label="中文" :label-width="formLabelWidth">
                <el-input v-model="form.region" ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false; form.name = ''; form.region = ''">取 消</el-button>
              <el-button type="primary" @click="add">确 定</el-button>
            </div>
          </el-dialog>
          <el-menu-item index="1" @click="dialogFormVisible = true">添加单词</el-menu-item>
          <el-menu-item index="2">切换词库</el-menu-item>
        </el-menu>
      </el-header>
      <el-main >
        <div align="center" style="margin-top: 100px">
          <h3>创建时间：{{ time }}</h3>
          <el-card class="box-card">
            <p style="float: left; margin-left: 10px; display: inline-block">
              <span>English&nbsp;&nbsp;</span>
              <el-switch
                v-model="value1"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              <el-tag
                  :type="this.value1==true?'success':'danger'"
                  effect="plain">
                {{ this.value1==true?english:'hidden' }}
              </el-tag>
              <el-button style="margin-left: 5px" size="mini" @click="read()"><i class="el-icon-video-play"/></el-button>
            </p>
            <p style="float: left; margin-left: 10px; display: inline-block">
              <span>中文&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <el-switch
                v-model="value2"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              <el-tag
                  :type="this.value2==true?'success':'danger'"
                  effect="plain">
                {{ this.value2==true?chinese:'已隐藏' }}
              </el-tag>
            </p>
            <div style="margin-top: 130px;">
              <el-button v-show="this.value1 || this.value2" type="info" round style="margin-right: 10px" @click="kill()">记住了</el-button>
              <el-button v-show="this.value1 || this.value2" type="success" round style="margin-left: 10px" @click="next()">下一个</el-button>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  name: 'Main',
  data(){
    return{
      time: "None",
      value1: true,
      value2: true,
      english: "",
      chinese: '',
      dialogFormVisible: false,
      form: {
        name: '',
        region: '',
      },
      formLabelWidth: '120px',
      library: localStorage.getItem("library"),
      wordList:[],
      currentWord:''
    }
  },
  methods: {
    read(){
      let au = document.getElementById('au')
      au.play()
    },
    handleSelect(key) {
      if(key === "2"){
        localStorage.removeItem("library")
        this.$router.replace('/')
      }
    },
    add(){
      if(this.form.name != '' && this.form.region != ''){
        let param = {
          english: this.form.name,
          chinese: this.form.region,
          library: this.library
        }
        let config = {
          method: 'post',
          url: this.$host + '/insert',
          headers: {
            'Content-Type': 'application/json'
          },
          data : param
        };
        const _this = this
        this.$ajax(config)
            .then(function (response) {
              if(response.data === true){
                _this.$message.success("添加成功！")
                _this.from.name = ''
                _this.form.region = ''
              }else{
                this.$message.warning("添加失败!")
              }
            })
            .catch(function (error) {
              console.log(error);
            });
      }else{
        this.$message.warning("添加失败，不能有空")
      }
      this.dialogFormVisible = false
    },
    getList(){
      let config = {
        method: 'post',
        url: this.$host + '/list?library=' + this.library,
        headers: { },
        data : ''
      };

      const _this = this
      this.$ajax(config)
          .then(function (response) {
            _this.wordList = response.data
            _this.getWord()
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    getWord(){
      this.currentWord = this.wordList[0];
      if(this.currentWord == null || this.currentWord === undefined){
        this.english = 'None'
        this.chinese = 'None'
        this.time = 'None'
        return
      }
      this.english = this.currentWord.english
      this.chinese = this.currentWord.chinese
      this.time = this.formatDate(new Date(this.currentWord.createTime))
      let mm = document.getElementById('mm')
      mm.innerHTML = ''
      let au = document.createElement('audio')
      let scr = document.createElement('source');
      scr.type = 'audio/mpeg';
      // 传参一个回调函数名给后端，方便后端返回时执行这个在前端定义的回调函数
      scr.src = 'https://tts.youdao.com/fanyivoice?word=' + this.english + '&le=eng&keyfrom=speaker-target'
      au.controls = false
      au.className = 'au'
      au.id = 'au'
      au.appendChild(scr)
      mm.appendChild(au)
    },
    next(){
      if(this.english === 'None'){
        this.$message.warning("词库里没有单词了！")
        return
      }
      let config = {
        method: 'post',
        url: this.$host + '/update',
        headers: { },
        data : this.currentWord
      };

      const _this = this
      this.$ajax(config)
          .then(function (response) {
            if(response.data === true){
              _this.wordList.splice(0, 1);
              if(_this.wordList.length === 0){
                _this.getList()
              }else{
                _this.getWord()
              }
            }
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    kill(){
      if(this.currentWord == null || this.currentWord === undefined){
        this.$message.warning("词库里没有单词了！")
        return
      }
      let config = {
        method: 'post',
        url: this.$host + '/delete',
        headers: { },
        data : this.currentWord
      };

      const _this = this
      this.$ajax(config)
          .then(function (response) {
            if(response.data === true){
              _this.wordList.splice(0, 1);
              if(_this.wordList.length === 0){
                _this.getList()
              }else{
                _this.getWord()
              }
            }
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    formatDate(now) {
      let year = now.getFullYear(),
          month = now.getMonth() + 1,
          date = now.getDate(),
          hour = now.getHours(),
          minute = now.getMinutes(),
          second = now.getSeconds();

      return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
  },
  created() {
    this.getList()
  }
}
</script>
<style>
.el-menu-demo{
  float: right;
}
.el-menu-demo .el-menu-item{
  font-size: 16px;
}

.box-card {
  width: 600px;
}
.el-tag{
  margin-left: 10px;
  font-size: 18px;
  width: 333px;
}
*{
  touch-action: none;
}
</style>